<template>
  <div class="flex h-full flex-col bg-#f7f9fc z-20 app-crud">
    <AppCard :border="false">
      <form
        class="flex justify-between"
        style="
          box-shadow:
            rgba(0, 0, 0, 0.1) 0 0 4px,
            rgba(9, 30, 66, 0.08) 0 1px 10px;
        "
      >
        <div class="flex-1 flex pb-12 pt-12 px-20">
          <div class="flex-1 flex">
            <query-item class="w-200" label="工序组">
              <a-select v-model:value="group" placeholder="请选择工序组" allow-clear class="w-150 h-30">
                <a-select-option v-for="g in groups" :value="g.id">{{g.name}}</a-select-option>
              </a-select>
            </query-item>
            <QueryItem>
              <a-input placeholder="请输入姓名" allow-clear v-model:value="worker"></a-input>
            </QueryItem>
            <QueryItem style="width: 280px">
              <a-range-picker v-model:value="date" class="w-260"></a-range-picker>
            </QueryItem>

            <a-space>
              <a-button-group>
                <a-button @click="onMonth(-1)">上一月</a-button>
                <a-button @click="onMonth(1)">下一月</a-button>
              </a-button-group>

              <a-button type="primary" @click="getData" :loading="loading">
                <template #icon><SearchOutlined></SearchOutlined></template>
                查询
              </a-button>
              <a-button @click="onExport">导出</a-button>
            </a-space>
          </div>
          <div class="flex-shrink-0">
            <a-space>
              <a-tooltip placement="bottom" title="重置" v-if="$slots.default">
                <a-button type="text" @click="handleReset">
                  <template #icon>
                    <ReloadOutlined></ReloadOutlined>
                  </template>
                </a-button>
              </a-tooltip>
              <slot name="action"></slot>
            </a-space>
          </div>
        </div>
      </form>
    </AppCard>

    <AppCard class="flex-1 mt-8 overflow-hidden relative" border>
      <a-spin v-if="loading" class="absolute top-0 left-0 right-0 bottom-0 z-100 pt-100"></a-spin>
      <div ref="reportEl" class="h-full"></div>
    </AppCard>
  </div>
</template>
<script setup lang="ts">
import AppCard from '../../../components/common/AppCard.vue'
import { getUserRecords } from '@/api/report.ts'
import { PivotTable, TYPES, themes } from '@visactor/vtable'
import { QueryItem } from '@/components/common'
import { SearchOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import useLoading from '@/hooks/loading.ts'
import { message } from 'ant-design-vue'
import { downloadExcel, exportVTableToExcel } from '@visactor/vtable-export'
import groupApi, { GroupDto } from '@/api/group.ts'

const reportEl = ref()
const { loading, setLoading } = useLoading()
let tableInstance:any = null
const date = ref([dayjs().startOf('month'), dayjs().endOf('month')])
const worker = ref<string | null>(null)
const group = ref<string | null>(null)
const groups = ref<GroupDto[]>([])

function getStyle() {
  return {
    bgColor(arg) {
      const rowHeaderPaths = arg.cellHeaderPaths.rowHeaderPaths
      if (rowHeaderPaths?.[1]?.value === '小计') {
       return '#E6F4FF'
      } else if (rowHeaderPaths?.[0]?.value === '合计') {
        return '#EEF1F5'
      }
      return '#FFFFFF'
    },
  }
}

function render(records: any) {
  const option = {
    theme: themes.ARCO,
    records: records,
    defaultRowHeight: 32,
    rows: [
      {
        dimensionKey: 'worker',
        title: '姓名',
      },
      {
        dimensionKey: 'styleName',
        title: '款式',
        headerStyle: {
          textStick: true,
          bgColor(arg) {
            if (arg.dataValue === '小计') {
              return '#E6F4FF'
            }
            return '#ECF1F5'
          },
        },
      },
      {
        dimensionKey: 'process',
        title: '工序',
        headerStyle: {
          textStick: true,
        },
      },
    ],
    indicators: [
      {
        indicatorKey: 'number',
        title: '数量',
        width: 'auto',
        style: getStyle(),
      },
      {
        indicatorKey: 'price',
        title: '工价(元)',
        width: 'auto',
        style: getStyle(),
      },
      {
        indicatorKey: 'amount',
        title: '工资(元)',
        width: 'auto',
        style: getStyle(),
        format: (rec) => {
          return Number(rec).toFixed(2)
        },
      },
    ],
    corner: {
      titleOnDimension: 'row',
      headerStyle: {
        textStick: true,
      },
    },
    defaultHeaderColWidth: [100, 220, 280, 'auto'],
    dataConfig: {
      aggregationRules: [
        {
          indicatorKey: 'price',
          aggregationType: TYPES.AggregationType.NONE,
        },
        {
          indicatorKey: 'number',
          aggregationType: TYPES.AggregationType.SUM,
        },
      ],
      totals: {
        row: {
          showGrandTotals: true,
          showSubTotals: true,
          subTotalsDimensions: ['worker'],
          grandTotalLabel: '合计',
          subTotalLabel: '小计',
        },
      },
    },
    widthMode: 'adaptive',
    bottomFrozenRowCount: 1,
    hover: {
      highlightMode: 'row',
    },
  }
  tableInstance = new PivotTable(reportEl.value, option)
}

function onMonth(add: number) {
  const d = dayjs(date.value[0].format('YYYY-MM-DD')).add(add, 'month')
  date.value = [d.startOf('month'), d.endOf('month')]

  getData()
}

function getData() {
  if (!date.value || date.value.length == 0) {
    return message.error('请选择时间！')
  }

  setLoading(true)
  getUserRecords({
    startDate: date.value[0].format('YYYY-MM-DD'),
    endDate: date.value[1].format('YYYY-MM-DD'),
    worker: worker.value,
    group: group.value
  }).then((rep) => {
    render(rep.data)
    setLoading(false)
  })
}

async function onExport() {
  if (tableInstance) {
    downloadExcel(await exportVTableToExcel(tableInstance), '生产报表' + dayjs().format('YYYYMMDDHHmmss'))
  }
}

onMounted(() => {

  groupApi.all().then(({ data })=> {
    groups.value = data;
  })

  getData();
})
</script>

<style scoped></style>
